package team.dmh.wx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import team.dmh.wx.entity.User;
import team.dmh.wx.mapper.UserMapper;
import team.dmh.wx.service.IUserService;
import team.dmh.wx.util.*;
import team.dmh.wx.vo.UserVO;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzk
 * @since 2018-10-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Override
    public boolean queryIsExistByUsername(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username)) != null ? true : false;
    }

    @Override
    public User queryForLogin(String username, String password) {
        User userResult=baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username).eq(User::getPassword,password));
        return  userResult!= null ? userResult : null;
    }

    @Override
    public UserVO register(User user) throws IOException, NoSuchAlgorithmException {
        String id=IDUtils.getInstance().nextId();
        //temp qrCode file path
        String qrCodePath="temp_imgs/"+id+"_qrcode.png";
        //generate temp file
        qrCodeUtils.createQRCode(qrCodePath,"wx_friend_qrcode:"+user.getUsername());
        MultipartFile qrCodeFile=FileUtils.fileToMultipart(qrCodePath);
        //upload
        String qrCodeUrl=fastDFSClient.uploadImg(qrCodeFile);
        user.setNickname(user.getUsername())
                .setId(id)
                .setImg(FileUtils.DEFAULT_IMG_PATH)
                .setImgBig(FileUtils.DEFAULT_IMG_PATH_BIG)
                .setPassword(MD5Utils.encrypt(user.getPassword()))
                .setQrcode(qrCodeUrl)
                ;
        baseMapper.insert(user);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}
